<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="产品名字" prop="productName">
        <el-input
          v-model="queryParams.productName"
          placeholder="请输入产品名字"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="产品状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择产品状态" clearable>
          <el-option
            v-for="dict in dict.type.pro_product_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['product:product:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['product:product:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['product:product:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['product:product:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="productList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="产品ID" align="center" prop="productId"/>
      <el-table-column label="产品名字" align="center" prop="productName"/>
      <el-table-column label="商品原价" align="center" prop="originalPrice"/>
      <el-table-column label="商品现价" align="center" prop="currentPrice"/>
      <el-table-column label="商品库存" align="center" prop="inventory"/>
      <el-table-column label="商品主图" align="center" prop="pic" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.pic" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="产品状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.pro_product_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['product:product:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['product:product:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改产品管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="70%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="商品主图" prop="pic">
              <image-upload v-model="form.pic"/>
            </el-form-item>
            <el-form-item label="产品状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio
                  v-for="dict in dict.type.pro_product_status"
                  :key="dict.value"
                  :label="dict.value"
                >{{ dict.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="产品分类" prop="categoryId">
              <el-cascader
                v-model="form.categoryId"
                :options="categoryTree"
                :props="{ children: 'children',label:'categoryName',value:'categoryId' }"
              ></el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="产品名字" prop="productName">
              <el-input v-model="form.productName" placeholder="请输入产品名字"/>
            </el-form-item>
            <el-form-item label="店铺名称" prop="shopId">
              <el-select v-model="form.shopId" placeholder="请选择店铺">
                <el-option
                  v-for="item in shopList"
                  :key="item.shopId"
                  :label="item.shopName"
                  :value="item.shopId">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="上架时间" prop="putAwayTime">
              <el-date-picker clearable
                              v-model="form.putAwayTime"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="请选择上架时间">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="产品卖点">
              <el-input v-model="form.brief" type="textarea" placeholder="请输入内容"/>
            </el-form-item>

            <el-form-item label="产品分组" prop="groupId">
              <el-select v-model="form.groupId"  placeholder="请选择">
                <el-option
                  v-for="item in groupList"
                  :key="item.groupId"
                  :label="item.groupName"
                  :value="item.groupId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="配送方式" prop="deliveryType">
              <el-radio-group v-model="form.deliveryType">
                <el-radio
                  v-for="dict in dict.type.pro_product_delivery_type"
                  :key="dict.value"
                  :label="dict.value"
                >{{ dict.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
            <!-- 查询运费表并把数据加入下拉框           -->
            <el-form-item label="运费设置" v-if="form.deliveryType==='0'">
              <el-select v-model="form.deliveryTemplateId" placeholder="请选择" @change="handleSelectChange">
                <el-option
                  v-for="item in transportList"
                  :key="item.transportId"
                  :label="item.transName"
                  :value="item.transportId">
                </el-option>
              </el-select>
            </el-form-item>



<!--            <el-divider content-position="center">商品规格</el-divider>
            <el-row :gutter="10" class="mb8">
              <el-col :span="1.5">
                <el-button icon="el-icon-plus" size="mini" @click="handleAddSpecification">添加</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button icon="el-icon-delete" size="mini" @click="handleDeleteSpecification">删除</el-button>
              </el-col>
            </el-row>
            <el-table :data="specificationList" :row-class-name="rowSpecificationIndex"
                      @selection-change="handleSpecificationSelectionChange" ref="specification">
              <el-table-column type="selection" width="30" align="center"/>
              <el-table-column label="序号" align="center" prop="index" width="50"/>
              <el-table-column label="规格名" prop="propName" width="150">
                <template slot-scope="scope">
                  <el-select v-model="scope.row.propName" placeholder="请选择属性名称">
                    <el-option
                      v-for="item in scope.row.specificationNameList"
                      :key="'propName'+item.specId"
                      :label="item.propName"
                      :value="item.specId">
                    </el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="属性值" align="center" prop="rule">
                <template v-slot="scope">
                  <el-select v-model="scope.row.valueName" multiple placeholder="请选择属性名称">
                    <el-option
                      v-for="item in scope.row.specificationValueList"
                      :key="'valueName'+item.valueId"
                      :label="item.valueName"
                      :value="item.valueId">
                    </el-option>
                  </el-select>
                </template>
              </el-table-column>
            </el-table>-->
            <!-- 规格表格sku的列配置 -->
            <el-table
              v-if="form.productId"
              :data="productSkuData"
              style="width: 100%">
              <el-table-column label="sku图片" align="center" prop="pic" width="100">
                <template slot-scope="scope">
                  <image-preview :src="scope.row.pic" :width="50" :height="50"/>
                </template>
              </el-table-column>
              <el-table-column
                prop="skuName"
                label="商品名称">
              </el-table-column>
              <el-table-column
                prop="price"
                label="销售价">
              </el-table-column>
              <el-table-column
                prop="oriPrice"
                label="市场价">
              </el-table-column>
              <el-table-column
                prop="actualStocks"
                label="库存">
              </el-table-column>
              <el-table-column
                prop="weight"
                label="商品重量(kg)">
              </el-table-column>
              <el-table-column
                prop="volume"
                label="商品体积(m3)">
              </el-table-column>
              <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-edit"
                    @click="forbidden(scope.row)"
                    v-hasPermi="['product:product:edit']"
                  >禁用
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-form-item label="产品详情">
              <editor v-model="form.content" :min-height="192" style="height: 300px"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {listProduct, getProduct, delProduct, addProduct, updateProduct} from "@/api/product/product";
import {listDetail} from "../../../api/outlet/detail";
import {listGroup} from "../../../api/product/group";
import {listCategory} from "../../../api/product/category";
import {listTransport} from "../../../api/outlet/transport";
import {listSpecification} from "../../../api/product/specification";

export default {

  name: "Product",
  dicts: ['pro_product_delivery_type', 'pro_product_status'],
  data() {
    return {
      //sku信息
      productSkuData:[],
      showTable: false, // 控制表格显示与隐藏
      tableData: [], // 表格数据
      // 新增表单中规格中的规格名选择的下拉框集合
      specificationNameList: [],
      //商家配送下拉选择
      transportList: [],
      //分类下拉树
      categoryTree: [],
      //分组下拉
      groupList: [],
      //店铺下拉
      shopList: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedSpecification: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 产品管理表格数据
      productList: [],
      // 规格管理表格数据
      specificationList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        productName: null,
        status: null,
      },
      // 表单参数
      form: {},
      //groupIds: [],

      // 表单校验
      rules: {
        productName: [
          {required: true, message: "产品名字不能为空", trigger: "blur"}
        ],
        pic: [
          {required: true, message: "商品主图不能为空", trigger: "blur"}
        ],
        status: [
          {required: true, message: "产品状态不能为空", trigger: "change"}
        ],
        categoryId: [
          {required: true, message: "分类ID不能为空", trigger: "blur"}
        ],
        groupId: [
          {required: true, message: "分组ID不能为空", trigger: "blur"}
        ],
      }
    };
  },
  watch: {
    specificationList: {
      handler(newVal) {
        newVal.forEach(v => {
          if (v.index) {
            this.specificationNameList.forEach(o => {
              if (o.specId === v.propName) {
                this.specificationList[v.index - 1].specificationValueList = o.specificationProductList;
              }
            })
          }
        })
      },
      deep: true
    }
  },
  created() {
    this.getList();
    /*店铺名称下拉*/
    listDetail(this.queryParams).then(response => {
      this.shopList = response.rows
    })
    /*分组下拉*/
    listGroup(this.queryParams).then(response => {
      this.groupList = response.rows
    })
    //分类下拉树
    listCategory(this.queryParams).then(response => {
      this.categoryTree = this.handleTree(response.data, "categoryId", "parentId");
      /*this.form.categoryId = this.handleTree(this.categoryTree, this.form.categoryId)
      console.info(this.form.categoryId)*/
    })
    //商家配送选择
    listTransport(this.queryParams).then(response => {
      this.transportList = response.rows
    })
    this.showSpecificationNameList()
  },
  methods: {
    //禁用操作
    forbidden(){

    },
    //规格名数据请求
    showSpecificationNameList() {
      listSpecification(this.queryParams).then(response => {
        this.specificationNameList = response.rows;
      });
    },
    //
    /** 查询产品管理列表 */
    getList() {
      this.loading = true;
      listProduct(this.queryParams).then(response => {
        this.productList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    //运费设置
    handleSelectChange(value) {
      // 根据选中的值来决定是否显示表格
      if (value) {
        this.showTable = true;
        // 根据选中的值来获取表格数据，可以通过接口请求或者其他方式获取
        // this.tableData = ...
      } else {
        this.showTable = false;
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        productId: null,
        productName: null,
        originalPrice: null,
        currentPrice: null,
        inventory: null,
        pic: null,
        status: null,
        categoryId: null,
        groupId: null,
        brief: null,
        deliveryType: null,
        details: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        shopId: null,
        putAwayTime: null,
        soldNum: null,
        content: null,
        images: null
      };
      this.specificationList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.productId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加产品管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const productId = row.productId || this.ids

      getProduct(productId).then(response => {
        this.form = response.data;
        //this.groupIds = []
        //this.groupIds.push(response.data.groupId)
        //this.groupIds=response.data.groupId
        this.productSkuData=response.data.skuAndProduct
        this.specificationList = response.data.specificationList;
        this.open = true;
        this.title = "修改产品管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.categoryId=this.form.categoryId[this.form.categoryId.length-1]
          this.form.specificationList = this.specificationList;
          if (this.form.productId != null) {
            updateProduct(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addProduct(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const productIds = row.productId || this.ids;
      this.$modal.confirm('是否确认删除产品管理编号为"' + productIds + '"的数据项？').then(function () {
        return delProduct(productIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 规格管理序号 */
    rowSpecificationIndex({row, rowIndex}) {
      row.index = rowIndex + 1;
    },
    /** 规格管理添加按钮操作 */
    handleAddSpecification() {
      let obj = {};
      obj.propName = "";
      obj.rule = "";
      obj.specificationNameList = this.specificationNameList;
      this.specificationList.push(obj);
    },
    /** 规格管理删除按钮操作 */
    handleDeleteSpecification() {
      if (this.checkedSpecification.length == 0) {
        this.$modal.msgError("请先选择要删除的规格管理数据");
      } else {
        const specificationList = this.specificationList;
        const checkedSpecification = this.checkedSpecification;
        this.specificationList = specificationList.filter(function (item) {
          return checkedSpecification.indexOf(item.index) == -1
        });
      }
    },
    /** 复选框选中数据 */
    handleSpecificationSelectionChange(selection) {
      this.checkedSpecification = selection.map(item => item.index)
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('product/product/export', {
        ...this.queryParams
      }, `product_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
